/**
* Created with IntelliJ IDEA.
* Description:
* User:DELL
* Date:2025-05-04
* Time:23:32
*/
public class Text {
    public ListNode reverseKGroup(ListNode head, int k) {
        //先求出需要逆序多少组
        int n=0;
        ListNode cur=head;
        while(cur!=null){
            cur=cur.next;
            n++;
        }
        n/=k;

        //重复n次长度为k的链表逆序
        ListNode newHead=new ListNode(0);
        ListNode prev=newHead;
        cur=head;
        for(int i=0;i<n;i++){
            ListNode tmp=cur;
            for(int j=0;j<k;j++){
                //头插链表
                ListNode next=cur.next;
                cur.next=prev.next;
                prev.next=cur;
                cur=next;
            }
            prev=tmp;
        }
        //处理剩余的链表
        prev.next=cur;
        return newHead.next;
    }
}
